package com.edu.demo.login.serviceImpl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import com.edu.demo.login.service.SessionProvider;
import com.edu.demo.login.utlis.Constants;

import redis.clients.jedis.Jedis;

/**
 * 保存用户名或验证码到Redis中
 * Session共享
 * @author lx
 *
 */
@Service
public class SessionProviderImpl implements SessionProvider{

	//redis注入
	@Autowired
	private RedisTemplate redisTemplate;
	

	private Integer exp = 30;
	public void setExp(Integer exp) {
		this.exp = exp;
	}

	@Override
	public void setAttribuerForUsername(String name, String value) {
		
		//保存用户名到Redis中
		//　K　：　CSESSIONID:Constants.USER_NAME   == name
		redisTemplate.opsForValue().set(name + ":" +  Constants.USER_NAME, value);
		//时间 
		
		redisTemplate.expire(name + ":" +  Constants.USER_NAME,  60*exp, TimeUnit.SECONDS);
	//	redisTemplate.expire(name + ":" +  Constants.USER_NAME, 60*exp);
	}

	@Override
	public String getAttributeForUsername(String name) {
		// TODO Auto-generated method stub
		//fbb2016
		String value = redisTemplate.opsForValue().get(name + ":" +  Constants.USER_NAME).toString();
		if(null != value){
			//时间 
			redisTemplate.expire(name + ":" +  Constants.USER_NAME, 60*exp, TimeUnit.SECONDS);
		}
		return value;
	}
	
	@Bean
	public RedisTemplate redisTemplateInit() {
		// 设置序列化Key的实例化对象
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		// 设置序列化Value的实例化对象
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		return redisTemplate;
	}

	@Override
	public void setAttribuerForPicCode(java.lang.String name, java.lang.String value) {
		
		        //保存用户名到Redis中
				//　K　：　CSESSIONID:Constants.USER_NAME   == name
				redisTemplate.opsForValue().set(name + ":" +  Constants.PICTURE_NAME, value);
				//时间 
				
				redisTemplate.expire(name + ":" +  Constants.PICTURE_NAME,  60*exp, TimeUnit.SECONDS);
	}

	@Override
	public String getAttribuerForPicCode(java.lang.String name) {
		
		return name;		
	}

	
}
